//
//  JPPostTaskController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/17.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "JPPostTaskController.h"
#import "JPAddressListController.h"
#import "DHAreaButton.h"
#import <SDWebImageDownloader.h>
#import <AlipaySDK/AlipaySDK.h>
#import "APRSASigner.h"
#import "APOrderInfo.h"
@interface JPPostTaskController ()<UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate,PGDatePickerDelegate,JPPayViewDelegate, CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *contentTxtField;
@property (weak, nonatomic) IBOutlet UITextField *priceTxtField;
@property (weak, nonatomic) IBOutlet UITextField *titleTxtField;
@property (weak, nonatomic) IBOutlet UITextField *hourAndPriceTxtField;
@property (weak, nonatomic) IBOutlet UITextField *roomAndPrice;
@property (weak, nonatomic) IBOutlet UITextField *hourTxtField;
@property (weak, nonatomic) IBOutlet UITextField *roomTxtField;
@property (weak, nonatomic) IBOutlet UIButton *numRoomBtn;
@property (weak, nonatomic) IBOutlet UIButton *workHourBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *clearAreaConsH;
@property (weak, nonatomic) IBOutlet UIView *clearAreaView;
@property (weak, nonatomic) IBOutlet UILabel *serviceTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *locLabel;
@property (weak, nonatomic) IBOutlet UIView *tipView;
@property (weak, nonatomic) IBOutlet UIButton *postButton;
@property(nonatomic ,strong)NSArray<DHClearArea *> *cleanList;
@property(nonatomic ,strong)DHAddressModel *addrModel; // 记录地址模型
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *postImgButtons;     // 上传图片按钮数组--根据selected来记录

@property(nonatomic ,strong)UIButton *currectPostImgButton;
@property(nonatomic ,strong)UIButton *selectedBtnIsCheckout; // 记录选中的是否退房按钮
@property(nonatomic ,strong)UIButton *selectedBtnMethodAccount; // 记录选中的结算方式按钮

@property(nonatomic,strong) UIImagePickerController *imagePicker; //声明全局的UIImagePickerController
@property(nonatomic ,strong)NSArray<DHAreaButton*> *cleanAreaButtons;

@property(nonatomic,strong)CYPasswordView *pwdView;

@property(nonatomic,strong)JPPayView *payView;


@end

@implementation JPPostTaskController

- (void)setChangeInfo:(DHDetailModel *)changeInfo
{
    _changeInfo = changeInfo;
    
    if (!changeInfo) {return;}
  
    [SDWebImageDownloader.sharedDownloader downloadImageWithURL:[NSURL URLWithString:changeInfo.logo] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
         [(UIButton *)self.postImgButtons.lastObject setImage:image forState:UIControlStateNormal];
    }];
    [SDWebImageDownloader.sharedDownloader downloadImageWithURL:[NSURL URLWithString:changeInfo.image] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        [(UIButton *)self.postImgButtons.firstObject setImage:image forState:UIControlStateNormal];
    }];
    
    self.locLabel.text = changeInfo.address;
    self.serviceTimeLabel.text = changeInfo.end_time;
    
    // 结算方式
    switch (changeInfo.pay_type.intValue) {
        case 1: // 数量
            [self selectedBtnSettleAcount:self.numRoomBtn];
            self.roomTxtField.text = changeInfo.pay_value;
            self.roomAndPrice.text = changeInfo.pay_unit;
            break;
            
        default:
            [self selectedBtnSettleAcount:self.workHourBtn];
            self.hourTxtField.text = changeInfo.pay_value;
            self.hourAndPriceTxtField.text = changeInfo.pay_unit;
            break;
    }
    
    // 标题
    self.titleTxtField.text = changeInfo.title;
    self.priceTxtField.text = changeInfo.price;
    self.contentTxtField.text = changeInfo.content;
}
- (void)setCleanList:(NSArray<DHClearArea *> *)cleanList
{
    _cleanList = cleanList;
    
    if (!(cleanList.count > 0)) {
        return;
    }
   
    [self createdCleanAreaButtonWithList:cleanList];
    
    [self.view layoutIfNeeded];
    [self.tableView reloadData];
}
#pragma mark: - 创建清洁区域按钮
- (void)createdCleanAreaButtonWithList:(NSArray *)list
{
    int margin = 30;//间隙
    int width = 100;//格子的宽
    int height = 25;//格子的高
    self.clearAreaConsH.constant = ((list.count - 1) / 3 + 1) * height;
    NSMutableArray *arrayM = [NSMutableArray array];
    UIImage *btnImg = [UIImage imageNamed:@"kuang"];
    UIImage *btnSelectedImg = [UIImage imageNamed:@"gou"];
    UIColor *btnTextColor = [UIColor colorWithRed:153.0f/255.0f green:153.0f/255.0f blue:153.0f/255.0f alpha:1];
    [list enumerateObjectsUsingBlock:^(DHClearArea * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         NSInteger row = idx / 3;
         NSInteger col = idx % 3;
         
         DHAreaButton *btn = [[DHAreaButton alloc]init];
         btn.frame = CGRectMake(30+col*(width+margin), row*(height+margin), width, height);
         [btn setTitle:obj.name forState:UIControlStateNormal];
         [btn setImage:btnImg forState:UIControlStateNormal];
         [btn setImage:btnSelectedImg forState:UIControlStateSelected];
         btn.titleLabel.font = [UIFont systemFontOfSize:14];
         btn.addrModel = obj;
         [btn setTitleColor:btnTextColor forState:UIControlStateNormal];
         [btn setImageEdgeInsets:UIEdgeInsetsMake(0, -5, 0, 0)];
         [btn addTarget:self action:@selector(clearAreaButtonClick:) forControlEvents:UIControlEventTouchUpInside];
         
         [arrayM addObject:btn];
         [self.clearAreaView addSubview:btn];
     }];
    self.cleanAreaButtons = arrayM.copy;
}





#pragma mark: - 清洁区域按钮（多选）
- (void)clearAreaButtonClick:(UIButton *)sender
{
    sender.selected = !sender.isSelected;
}
#pragma mark: - 实例化方法
+ (instancetype)postTaskVC
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"JPPostTaskController" bundle:nil];
    JPPostTaskController *vc = [sb instantiateViewControllerWithIdentifier:@"postTaskID"];
    return vc;
}
#pragma mark: - 上传照片按钮监听 / 任务详情上传图片监听 -
- (IBAction)postImButtonClick:(UIButton *)sender
{
    self.currectPostImgButton.selected = NO;
    sender.selected = YES;
    self.currectPostImgButton = sender;
    //自定义消息框
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    sheet.tag = 2550;
    //显示消息框
    [sheet showInView:self.view];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self loadCleanAreaList];
    [self loadPayList];
    

    self.pwdView = [[CYPasswordView alloc] init];
    self.pwdView.title = @"输入支付密码";
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(hiddenPayView) name:kHiddenPayViewNoticfication object:nil];
    
    self.payView = [[JPPayView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY([UIApplication.sharedApplication keyWindow].frame), kScreenWidth, kScreenHeight)];
    self.payView.delegate = self;
   // self.payView.backgroundColor = [UIColor redColor];
    [[UIApplication.sharedApplication keyWindow] addSubview:self.payView];
}

#pragma mark: - JPPayViewDelegate
- (void)payView:(JPPayView *)view balancePay:(NSMutableDictionary *)dict
{
   
    [UIView animateWithDuration:0.25 animations:^{
        self.payView.transform = CGAffineTransformIdentity;
    }];
    
    [self.pwdView showInView:[UIApplication.sharedApplication keyWindow]];
    __weak typeof(self) WeakSelf = self;
    self.pwdView.finish = ^(NSString *password)
    {
        [WeakSelf.pwdView hideKeyboard];
        [WeakSelf.pwdView startLoading];
        dict[@"paypwd"] = password;
        
        [DHNetworkManager.shareManager requestWithMethod:MethodPost
                                               UrlString:kPayBalanceUrl params:dict.copy
                                              completion:^(id json, BOOL isSuccess)
         {
             [WeakSelf.pwdView stopLoading];
             if (!isSuccess) {
                 [SVProgressHUD showErrorWithStatus:@"请检查网络"];
                 [WeakSelf.pwdView requestComplete:YES];
                 [WeakSelf.pwdView hide];return ;
             }
             id tem = json[@"datas"];
             if (tem[@"error"]) {
                 [SVProgressHUD showErrorWithStatus:tem[@"error"]];
                 [WeakSelf.pwdView requestComplete:YES];
                [WeakSelf.pwdView hide];return ;
             }
             [SVProgressHUD showSuccessWithStatus:tem[@"succ"]];
             [WeakSelf.pwdView hide];


             [WeakSelf.pwdView requestComplete:YES];
         }];
    };
}
- (void)payView:(JPPayView *)view aliPay:(NSMutableDictionary *)dict
{
    [UIView animateWithDuration:0.25 animations:^{
        self.payView.transform = CGAffineTransformIdentity;
    }];
    // 重要说明
    // 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    // 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    // 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = @"";
    
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = @"";
    NSString *rsaPrivateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"缺少appId或者私钥,请检查参数设置"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction *action){
                                                           
                                                       }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{ }];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    APOrderInfo* order = [APOrderInfo new];
    
    // NOTE: app_id设置
    order.app_id = appID;
    
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定
    order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [APBizContent new];
    order.biz_content.body = @"我是测试数据";
    order.biz_content.subject = @"1";
    order.biz_content.out_trade_no = @"服务器返回的订单号"; //订单ID（由商家自行制定）
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", 0.01]; //商品价格
    
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    NSLog(@"orderSpec = %@",orderInfo);
    
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    NSString *signedString = nil;
    APRSASigner* signer = [[APRSASigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
    if ((rsa2PrivateKey.length > 1)) {
        signedString = [signer signString:orderInfo withRSA2:YES];
    } else {
        signedString = [signer signString:orderInfo withRSA2:NO];
    }
    
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"alisdkdemo";
        
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                 orderInfoEncoded, signedString];
        
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
    }
}
- (void)dealloc
{
    [NSNotificationCenter.defaultCenter removeObserver:self];
}

#pragma mark: - 隐藏支付界面通知
- (void)hiddenPayView
{
    [UIView animateWithDuration:0.25 animations:^{
        self.payView.transform = CGAffineTransformIdentity;
    }];
}
- (void)loadPayList
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    [DHNetworkManager.shareManager requestWithMethod:MethodPost UrlString:kPayListUrl params:dict
                                          completion:^(id json, BOOL isSuccess)
    {
        if (!isSuccess) {
            [SVProgressHUD showInfoWithStatus:@"请检查网络"];
            return ;
        }
        self.payView.payMemetList = [NSArray yy_modelArrayWithClass:[JPPayMentModel class] json:json[@"datas"]];
    }];
}
#pragma mark: - 发布任务的按钮监听
- (IBAction)postTaskButtonClick:(UIButton *)sender
{
    
    NSMutableArray *imgArray = [NSMutableArray array];
   // __weak typeof(imgArray) WeakImgArray = imgArray;
    [self.postImgButtons enumerateObjectsUsingBlock:^(UIButton *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.currentImage) {
            [imgArray addObject:obj];
        }
    }];
    
    NSMutableArray *clearModelList = [NSMutableArray array];
    [self.cleanAreaButtons enumerateObjectsUsingBlock:^(DHAreaButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
    {
        if (obj.isSelected) {
            [clearModelList addObject:[obj.addrModel ID]];
        }
    }];
    if (!self.selectedBtnMethodAccount) {
        [SVProgressHUD showInfoWithStatus:@"请选择结算方式"];
        return;
    }
    if (!self.selectedBtnIsCheckout) {
        [SVProgressHUD showInfoWithStatus:@"请选择是否退房"];
        return;
    }
    if (!(clearModelList.count > 0)) {
        [SVProgressHUD showInfoWithStatus:@"清洁区域，至少选择一个"];
        return;
    }
    if (imgArray.count > 2) {
        [SVProgressHUD showInfoWithStatus:@"请上传图像,缺少图像!"];
        return;
    }
    if (!self.addrModel) {
        [SVProgressHUD showInfoWithStatus:@"请选择服务地址"];
        return;
    }
    if ([self.serviceTimeLabel.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"请选择服务时间"];
        return;
    }
    
    if (self.selectedBtnMethodAccount.tag == 1)
    {
        if (!self.roomTxtField.hasText) {
            [SVProgressHUD showInfoWithStatus:@"请选择填写结算方式"];
            return;
        }
        if (!self.roomAndPrice.hasText) {
            [SVProgressHUD showInfoWithStatus:@"请选择填写结算方式"];
            return;
        }
    }else{
        if (!self.hourTxtField.hasText) {
            [SVProgressHUD showInfoWithStatus:@"请选择填写结算方式"];
            return;
        }
        if (!self.hourAndPriceTxtField.hasText) {
            [SVProgressHUD showInfoWithStatus:@"请选择填写结算方式"];
            return;
        }
    }
    if (!self.titleTxtField.hasText) {
        [SVProgressHUD showInfoWithStatus:@"请输入标题"];
        return;
    }
    if (!self.priceTxtField.hasText) {
        [SVProgressHUD showInfoWithStatus:@"请输入赏金"];
        return;
    }
    if (!self.contentTxtField.hasText) {
        [SVProgressHUD showInfoWithStatus:@"请输入详细描述"];
        return;
    }
    
    //NSString *url = @"http://jpjd.cnaite.cn/mobile/index.php?act=hotel_cleaning&op=addClearTask";

//    NSMutableArray *dataList = [NSMutableArray array];
//    NSMutableArray *imgNameList = [NSMutableArray array];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"key"] = DHNetworkManager.shareManager.userAccount.key;
//    NSData *data1 = UIImageJPEGRepresentation([imgArray.firstObject currentImage], 1);
//    NSData *data2 = UIImageJPEGRepresentation([imgArray.lastObject currentImage], 1);
//    NSString *imgName1 = @"image";
//    NSString *imgName2 = @"logo";
//    [imgNameList addObject:imgName1];
//    [imgNameList addObject:imgName2];
//    [dataList addObject:data1];
//    [dataList addObject:data2];
//    params[@"image"] = data1;
//    params[@"logo"] = data2;
    params[@"title"] = self.titleTxtField.text;
    params[@"address_id"] = self.addrModel.address_id;
    params[@"end_time"] = self.serviceTimeLabel.text;
    params[@"clear_area"] = [clearModelList componentsJoinedByString:@","];
    params[@"is_leave"] = [NSString stringWithFormat:@"%zd",self.selectedBtnIsCheckout.tag];
    params[@"pay_type"] = [NSString stringWithFormat:@"%zd",self.selectedBtnMethodAccount.tag];
    params[@"pay_value"] = (self.selectedBtnMethodAccount.tag == 1) ? self.roomTxtField.text : self.hourTxtField.text;
    params[@"pay_unit"] = (self.selectedBtnMethodAccount.tag == 1) ? self.roomAndPrice.text : self.hourAndPriceTxtField.text;
    params[@"price"] = self.priceTxtField.text;
    params[@"content"] = self.contentTxtField.text;
   
    
    [self postUserImageFormDateWith:params.copy];
}
#pragma mark -- 上传头像Data

- (NSString*)returnFielName{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat =@"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
    return fileName;
}
- (void)postUserImageFormDateWith:(NSDictionary *)param{
    
    NSMutableArray *imgArray = [NSMutableArray array];
    // __weak typeof(imgArray) WeakImgArray = imgArray;
    [self.postImgButtons enumerateObjectsUsingBlock:^(UIButton *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.currentImage) {
            [imgArray addObject:obj];
        }
    }];
    
//    NSString * sexString =[self.sexSelectButton.titleLabel.text isEqualToString:@"男"]?@"1":@"0";
//
//    NSDictionary *dict = @{@"key":[UserManager shareUser].key, @"mobile":self.phoneTextField.text,@"level_id":self.VIP_id,@"level_name":self.rankTextField.text,@"tuijian_member_name":self.recommenTextField.text,@"auth_name":self.realNameTextField.text,@"auth_card":self.idCarTextField.text,@"auth_sex":sexString};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/plain", nil];
    //image
    NSData *imgData1 = nil;
    imgData1 =UIImageJPEGRepresentation([imgArray.firstObject currentImage],1);
    if ([imgData1 length]/1024<=100) {
        imgData1 =UIImageJPEGRepresentation([imgArray.firstObject currentImage],1);
        
    }else{
        
        imgData1 =UIImageJPEGRepresentation([self compressImage:[imgArray.firstObject currentImage] toByte:100*1024],0.5);
    }
    //logo
    NSData *imgData2 = nil;
    
    imgData2 =UIImageJPEGRepresentation([imgArray.lastObject currentImage],1);
    if ([imgData2 length]/1024<=100) {
        imgData2 =UIImageJPEGRepresentation([imgArray.lastObject currentImage],1);
        
    }else{
        
        imgData2 =UIImageJPEGRepresentation([self compressImage:[imgArray.lastObject currentImage] toByte:100*1024],0.5);
    }
   
    NSArray *nameArray = @[@"image",@"logo"];
    [manager POST:@"http://jpjd.cnaite.cn/mobile/index.php?act=hotel_cleaning&op=addClearTask"
       parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
           
           
           
           [formData appendPartWithFileData:imgData1
                                       name:nameArray[0]
                                   fileName:[self returnFielName]
                                   mimeType:@"image/jpeg"];
           [formData appendPartWithFileData:imgData2
                                       name:nameArray[1]
                                   fileName:[self returnFielName]
                                   mimeType:@"image/jpeg"];
         
           
           
       } progress:nil
          success:^(NSURLSessionTask *task, id responseObject) {
              
              //  NSString * errorStr;
              id temp = responseObject[@"datas"];
              
              if (temp[@"succ"])
              {
                  NSMutableDictionary *dictM = [NSMutableDictionary dictionaryWithDictionary:temp];
                  dictM[@"price"] = self.priceTxtField.text;
                  dictM[@"title"] = self.titleTxtField.text;
                  [SVProgressHUD showSuccessWithStatus:temp[@"succ"]];
                  self.payView.dictM = dictM.copy;
                  [UIView animateWithDuration:0.25 animations:^{
                      self.payView.transform = CGAffineTransformTranslate(self.payView.transform, 0, -self.payView.bounds.size.height);
                  }];
                  
              }else if (temp[@"error"]){
                  [SVProgressHUD showErrorWithStatus:temp[@"error"]];
              }
              
             // [self.navigationController popViewControllerAnimated:true];
          }
     
          failure:^(NSURLSessionTask *task, NSError *error) {
              NSLog(@"error:%@", error);
              
              
              
          }];
    
    
    
    
}
- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    
    
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    
    UIImage *resultImage = [UIImage imageWithData:data];
    
    if (data.length < maxLength)
        
        return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        
    }
    
    return resultImage;
}

#pragma mark: - 加载清洁区域数据
- (void)loadCleanAreaList
{
    if (!DHNetworkManager.shareManager.userAccount.key) {
        [SVProgressHUD showInfoWithStatus:@"请登录"];
        return;
    }
    
    [DHNetworkManager.shareManager requestWithMethod:MethodGet
                                           UrlString:kCleanAreaUrl
                                              params:@{@"key":DHNetworkManager.shareManager.userAccount.key}
                                          completion:^(id json, BOOL isSuccess)
     {
         if (!isSuccess) {
             [SVProgressHUD showInfoWithStatus:@"请检查网络"];
             return ;
         }
         self.cleanList = [NSArray yy_modelArrayWithClass:[DHClearArea class] json:json[@"datas"][@"list"]];
         [self.tableView reloadData];
     }];
}
#pragma mark: - prepareForSegue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    JPAddressListController *vc = segue.destinationViewController;
    vc.selectedAdrBlock = ^(DHAddressModel *model)
    {
        self.locLabel.text = model.address;
        self.addrModel = model;
    };
}
#pragma mark: - 结算方式按钮选择监听(单选)
- (IBAction)selectedBtnSettleAcount:(UIButton *)sender
{
    self.selectedBtnMethodAccount.selected = false;
    sender.selected = true;
    self.selectedBtnMethodAccount = sender;
}
#pragma mark: - 是否退房按钮事件监听(单选)
- (IBAction)isCheckoutButtonClick:(UIButton *)sender
{
    self.selectedBtnIsCheckout.selected = false;
    sender.selected = YES;
    self.selectedBtnIsCheckout = sender;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
        [self setupNavBar];
}
#pragma mark: - 设置界面
- (void)setupUI
{

    self.tipView.layer.masksToBounds = true;
    self.tipView.layer.cornerRadius = 6;
    self.postButton.layer.masksToBounds = true;
    self.postButton.layer.cornerRadius = 6;
    self.tableView.tableFooterView = [UIView new];
}
#pragma mark: - 设置导航栏
- (void)setupNavBar
{
    self.navigationController.navigationBar.hidden = false;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:222.0f/255.0f green:60.0f/255.0f blue:50.0f/255.0f alpha:1];
    self.title = @"任务发布";
    [self.navigationController.navigationBar setTintColor:UIColor.whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
}
#pragma mark: - table view delegate
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [self createdHeaderViewWithSection:section];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 添加服务时间
    if (indexPath.section == 0 && indexPath.row == 2) {
        PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
        PGDatePicker *datePicker = datePickManager.datePicker;
        datePicker.delegate = self;
        datePicker.datePickerMode = PGDatePickerModeDateHourMinute;
        [self presentViewController:datePickManager animated:false completion:nil];
        
        //设置取消按钮的字
        datePickManager.cancelButtonText = @"取消";
        //设置确定按钮的字
        datePickManager.confirmButtonText = @"确定";
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    return 160;
                    break;
                    
                default:
                    return 54;
                    break;
            }
            break;
        case 1:
            return self.clearAreaConsH.constant + 50;
            break;
        case 2:
            return 87;
            break;
        case 3:
            return 450;
            break;
        default:
            return 0;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 0 ;
            break;
            
        default:
            return 54;
            break;
    }
}
#pragma mark: - PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents
{
    NSString *serviceTime = [NSString stringWithFormat:@"%zd-%02zd-%zd %02zd:%02zd",dateComponents.year,dateComponents.month,dateComponents.day,dateComponents.hour,dateComponents.minute];
    
    self.serviceTimeLabel.text = serviceTime;
}
#pragma mark: - 创建headerView
- (UIView *)createdHeaderViewWithSection:(NSInteger)section
{
    NSString *headerTitle;
    switch (section) {
        case 1:
            headerTitle = @"    清洁区域";
            break;
        case 2:
            headerTitle = @"    结算方式";
            break;
        case 3:
            headerTitle = @"    任务详情";
            break;
        default:
            break;
    }
    UILabel *label = [[UILabel alloc] init];
    label.text = headerTitle;
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = UIColor.redColor;
    return label;
}

#pragma mark -消息框代理实现-
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 2550) {
        NSUInteger sourceType = 0;
        // 判断系统是否支持相机
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            imagePickerController.delegate = self; //设置代理
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = sourceType; //图片来源
            if (buttonIndex == 0) {
                //拍照
                sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
                
            }else if (buttonIndex == 1) {
                //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
            }else if (buttonIndex == 2){
                
                return;
            }
        }else {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
    }
}
#pragma mark -实现图片选择器代理-（上传图片的网络请求也是在这个方法里面进行，这里我不再介绍具体怎么上传图片）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //通过key值获取到图片
    
    //上传图片到服务器--在这里进行图片上传的网络请求，这里不再介绍
    //  ......
    [self.postImgButtons enumerateObjectsUsingBlock:^(UIButton *btn, NSUInteger idx, BOOL * _Nonnull stop)
    {
        if (btn.isSelected) {
            [btn setImage:image forState:UIControlStateNormal];
        }
    }];
}
@end
